import '@babel/polyfill';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import gsap from 'gsap';
import * as dat from 'dat.gui';
import * as CANNON from 'cannon-es';

//物理

//场景
const scene = new THREE.Scene();

//相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 200);
camera.position.set(0, 0, 20);
scene.add(camera);

//渲染器
const renderer = new THREE.WebGL1Renderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);


const sphereGoemetry = new THREE.SphereGeometry(1, 20, 20);
const material = new THREE.MeshStandardMaterial();
const sphere = new THREE.Mesh(sphereGoemetry, material);
sphere.position.set(0, 1, 0);
scene.add(sphere);

const floor = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), new THREE.MeshStandardMaterial());
floor.rotation.x = -Math.PI / 2;
floor.position.y = -5;
scene.add(floor);

const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);

//物理世界
const world = new CANNON.World();
world.gravity.set(0, -9.8, 0);

const sphereShape = new CANNON.Sphere(1);
const sphereBody = new CANNON.Body({
    shape: sphereShape,
    position: new CANNON.Vec3(0, 10, 0),
    mass: 1,//质量
    material: new CANNON.Material()
});
world.addBody(sphereBody);

const floorShape = new CANNON.Plane();
const floorBody = new CANNON.Body();
floorBody.addShape(floorShape);
floorBody.material = new CANNON.Material();
floorBody.mass = 0;
floorBody.position.set(0, -5, 0);
//物理世界旋转
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
world.addBody(floorBody);

const defaultContactMaterial = new CANNON.ContactMaterial(
    sphereBody.material,
    floorBody.material,
    {
        friction: 0.1,
        restitution: 0.5
    }
);
world.addContactMaterial(defaultContactMaterial);

const hitSound = new Audio('./assets/metalHit.mp3');
//监听碰撞
sphereBody.addEventListener('collide', (event) => {
    const hitStrength = event.contact.getImpactVelocityAlongNormal();
    if (hitStrength > 1) {
        hitSound.currentTime = 0;
        hitSound.play();
    }
});



//控制
const orbitControls = new OrbitControls(camera, renderer.domElement);
orbitControls.enableDamping = true;

//坐标轴
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);


//帧动画
const clock = new THREE.Clock();
function animate() {
    const time = clock.getDelta();
    //推进物理世界
    world.step(1 / 144, time);
    sphere.position.copy(sphereBody.position);

    orbitControls.update();
    renderer.render(scene, camera);
    requestAnimationFrame(animate);
};
animate();

//窗口调整侦听
window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
});



